import React from 'react';
import Redirect from 'umi/redirect';
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
import Authorized from '@/utils/Authorized';
import { isLogin } from '@/utils/utils'
import { checkPermissions } from '@/components/Authorized/CheckPermissions'

const hasPermission = JSON.parse(localStorage.getItem('hasSearchBtn'))

const getRouteAuthority = (path, routeData) => {
  let authorities;
  
  routeData.forEach(route => {
    // match prefix    
    if (pathToRegexp(`${route.path}(.*)`).test(path)) {
      // exact match
      if (route.path === path) {        
        authorities = hasPermission || authorities;
      } // get children authority recursively

      if (route.children) {
        authorities = getRouteAuthority(path, route.children) || authorities;
      }
    } else {
      authorities = hasPermission || authorities;
    }
  });  
  return authorities;
};

const AuthComponent = ({
  children,
  route = {
    routes: [],
  },
  user,
  global,
}) => {
  const { location } = children.props;
  const { menus } = global
    
  return (
    <Authorized
      authority={getRouteAuthority(location.pathname, menus) || ''}
      noMatch={isLogin ? <Redirect to="/exception/403" /> : <Redirect to="/user/login" />}
    >
      {children}
    </Authorized>
  );
};

export default connect(({ user, global }) => ({
  user,
  global,
}))(AuthComponent);
